import { fetchLogin, fetchUserInfo } from "@/api";


export default {
    namespaced: true,
    state: {
        token: localStorage.getItem('token'),
        userinfo: {}
    },
    mutations: {
        updateToken(state, token) {
            state.token = token
        },
        quitdataToken(state, payload) {
            state.token = payload
        },
        updateUserInfo(state, payload) {
            state.userinfo = payload
        }
    },
    actions: {
        login({ commit }, data) {
            return new Promise((resolve, reject) => {
                fetchLogin(data).then(res => {
                    if (res.err > 0) {
                        reject(res)
                        return;
                    }
                    commit('updateToken', res.token)
                    localStorage.setItem('token', res.token)
                    resolve()
                })
            })
        },
        quit({ commit }) {
            commit('quitdataToken', null)
            localStorage.removeItem('token')
        },
        getUserInfo({ commit }) {
            fetchUserInfo().then(res => {
                commit('updateUserInfo', res.userinfo)
            })
        }
    }
}

// 把token存储在 localStorage与vuex中 (或cookie与vuex中)